package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    //保存和更新员工操作
    public void saveOrUpdate(Employee record) {
        if (record.getId() == null) {
            String password = record.getPassword();
            //安全操作 密码不为null的时候 才能加密
            if(password != null){
                //密码加密 (把用户名当做盐 并且加密2次)
                Md5Hash hash = new Md5Hash(password,record.getUsername(),2);
                //设置加密后的密码
                record.setPassword(hash.toString());
            }
            //设置新增员工的状态默认为true
            record.setState(true);
            employeeMapper.insert(record);
        } else {
            //打破关系
            employeeMapper.deleteRoleRelation(record.getId());
            employeeMapper.updateByPrimaryKey(record);
        }
        for (Role role : record.getRoles()) {
            employeeMapper.insertRoleRelation(record.getId(),role.getId());
        }
    }

    //查询单个员工操作
    public Employee selectByPrimaryKey(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }


    //员工列表操作
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int count = employeeMapper.queryCount(qo);
        if (count == 0) {
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<Employee> data = employeeMapper.queryList(qo);
        return new PageResult(count, data);
    }

    /**
     * 用户名校验
     * @param username 传入的用户名
     * @param id
     * @return true or false
     */
    public Boolean validateName(String username, Long id) {
        //接受传入的用户名
        Employee emp = employeeMapper.selectByUsername(username);
        //如果emp找不到 用户名不存在   验证通过 返回true
        //如果前台传过来的id 和数据库查询到id相同 则是相同的用户 在做编辑操作的时候 验证也通过 返回true
        return  emp == null || emp.getId() == id;
    }

    public void changeState(Long id) {
        employeeMapper.changeState(id);
    }

    //根据id重置密码
    public void resetPassword(Long id) {
        employeeMapper.resetPassword(id);
    }

    /**
     * 根据用户名查询用户信息
     * @param principal
     * @return
     */
    public Employee selectByUsername(String principal) {
        return employeeMapper.selectByUsername(principal);
    }

    @Override
    public List<Employee> selectTeacher() {
        return employeeMapper.selectTeacher();
    }
}
